package com.github.dote.mio.ack;

import com.github.dote.mio.client.IOClient;
import com.github.dote.mio.protocal.Packet;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class AckReceiveTask {

    private final Map<String, Long> ackId2Timestamp = new ConcurrentHashMap<>();
    private Timer timer = null;
    private IOClient client;
    private int ackTimeout=3;
    private int checkInterval = 0;

    public AckReceiveTask(IOClient client) {
        this.client = client;
        this.ackTimeout=client.getConfig().getAckTimeout();
        checkInterval = ackTimeout * 100000;
    }

    private void doTaskOnece() {
        Iterator<Map.Entry<String, Long>> entryIt = ackId2Timestamp.entrySet().iterator();
        while(entryIt.hasNext())
        {
            Map.Entry<String, Long> entry = entryIt.next();
            String key = entry.getKey();
            long value = entry.getValue();
            long delta = System.currentTimeMillis() - value;
            if(delta >= ackTimeout*1000)
            {

                ackId2Timestamp.remove(key);
            }
        }
    }


    public AckReceiveTask startup(boolean immediately) {
        stop();

        timer = new Timer(true);
        timer.scheduleAtFixedRate(new TimerTask() {
                                      @Override
                                      public void run() {
                                          doTaskOnece();
                                      }
                                  }
                , immediately ? 1 : checkInterval
                , checkInterval);

        return this;
    }

    public void stop() {
        if (timer != null) {
            try {
                timer.cancel();
            } finally {
                timer = null;
            }
        }
    }

    public boolean isRunning() {
        return timer != null;
    }

    public boolean exist(String ackId) {
        return ackId2Timestamp.get(ackId) != null;
    }

    public void put(String ackId) {
        if(!ackId2Timestamp.containsKey(ackId))
        ackId2Timestamp.put(ackId,System.currentTimeMillis());
    }

    public boolean hasRecieved(String ackId)
    {
        return ackId2Timestamp.containsKey(ackId);
    }
}
